layui.config({
    base: CXL.ctxPath + '/layuiadmin/' //静态资源所在路径
}).extend({
    index: 'lib/index' //主入口模块
}).use(['table', 'laydate', 'form', 'layer', 'element'], function () {
    var admin = layui.admin;
    var table = layui.table;
    var laydate = layui.laydate;
    var $ = layui.$;
    var form = layui.form;
    let element = layui.element;
    let router = layui.router();

    var loadMaterialFlag = false;

    initFirst();

    function initFirst() {
        initMaterialSelect();

    }

    function initMaterialSelect() {
        let materialSelect1 = $('#materialTypeSelect1');
        getMaterialForInput(materialSelect1, form);
        let outportSelect1 = $('#outportStoreSelect1');
        getOutportForInput(outportSelect1, form);
    }

    form.on('select(WorkModeSelectFilter)', function (data) {
        if (data.value == "load") {
            $("#outportStoreSelect1").show();
        } else {
            $("#outportStoreSelect1").hide();
        }
        element.render();
        form.render('select');
    });
//监听提交任务表单提交
    form.on('submit(submitArtificialTask)', function (data) {
        postArtificialTask(data);
        return false;
    });

    //提交人工任务
    function postArtificialTask(data) {
        let inputDataJson = JSON.stringify(data.field);
        $.ajax({
            url: CXL.ctxPath + '/artificialTask/postTask',
            method: 'POST',
            datatype: 'JSON',
            data: {
                inputData: inputDataJson,
            },
            success: function (res) {
                if (res.success) {
                    CXL.success("任务提交成功!");
                    table.reload(Page.tableId);
                } else {
                    CXL.error(res.msg);
                }
            },
            fail: function () {
                CXL.error("网络错误！");
            }
        });
    }

    /**
     * 表格参数
     */
    var Page = {
        tableId: 'artificialTable',
        url: CXL.ctxPath + '/artificialTask/datagrid',
        toolbar: '#artificial-table-toolbar',
        where: {field: 'id', order: 'desc'},
        initColumn: function () {
            return [[
                {type: 'numbers'}
                , {field: 'id', title: 'ID', hide: true, width: 80}
                , {field: 'craneId', title: '天车编号', width: 120}
                , {
                    field: 'workType', title: '任务类型', width: 120, templet: function (d) {
                        if (d.workType == "load") {
                            res = "上料"
                        } else if (d.workType == "mix") {
                            res = "混料"
                        }
                        return res;
                    }
                }
                , {field: 'frequency', title: '总次数', width: 120}
                , {field: 'progress', title: '进度', width: 120}
                , {field: 'materialName', title: '物料类型', width: 120}
                , {
                    field: 'pause', title: '状态', width: 120, templet: function (d) {
                        if (d.pause == true) {
                            res = "暂停"
                        } else {
                            res = "正常"
                        }
                        return res;
                    }
                }
                , {fixed: 'right', title: '操作', toolbar: '#artificial-table-toolbar', width: 170}

            ]];
        },
        deleteUrl: CXL.ctxPath + "/artificialTask/delete",
        changeStatusUrl: CXL.ctxPath + "/artificialTask/changeTaskStatus",
    };

    /**
     * 监听表格工具事件
     */
    table.on('tool(artificialTableFilter)', function (obj) {
        //获得当前行数据
        var data = obj.data;
        //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var layEvent = obj.event;

        //查看操作
        if (layEvent === 'detail') {
            Page.openDetail(obj);
        }
        //删除操作
        else if (layEvent === 'delete') {
            Page.deleteAction(obj);
        }
        //编辑操作
        else if (layEvent === 'view') {
            Page.openEdit(data);
        } else if (layEvent === 'createWork') {
            Page.createWork(data);
        } else if (layEvent === 'pause') {
            Page.pauseTask(data);
        } else if (layEvent === 'continue') {
            Page.continueTask(data);
        }
    })
//暂停任务
    Page.pauseTask = function (data) {
        parent.layer.confirm('确定要暂停任务吗', function (index) {
            let artificialId = data.id;
            updateTaskStatus(artificialId,1);
            layer.close(index);
    });
    }
//继续任务
    Page.continueTask = function (data) {
        updateTaskStatus(data.id,0);
        table.reload(Page.tableId);
    }

    //删除任务
    Page.deleteAction = function (obj) {
        console.log(obj);
        parent.layer.confirm('真的确定要删除么', function (index) {

            //提交 Ajax进行后端删除
            $.ajax({
                type: "post",
                url: Page.deleteUrl,
                data: {id: obj.data.id},
                success: function (res) {
                    if (res.success) {
                        CXL.success(res.msg);
                        // layer.msg(res.msg);
                        //表格删除
                        obj.del();
                        table.reload(Page.tableId);
                        // table.reload();
                    } else {
                        CXL.warn(res.msg);
                        // layer.msg(res.msg);
                    }
                }
            });

            layer.close(index);
        });
    }


    /**
     * 页面查询
     */
    Page.searchAction = function () {
        let queryData = {};
        //查询字段
        if ($("#craneidinput").val() != 0) {
            queryData['craneId_begin'] = parseInt($("#craneidinput").val());
            queryData['craneId_end'] = parseInt($("#craneidinput").val());
        } else {
            queryData['craneId_begin'] = 1;
            queryData['craneId_end'] = 4;
        }
        table.reload(Page.tableId, {page: {curr: 1}, where: queryData});
    }


    /**
     * 页面查询条件的重置
     */
    Page.resetAction = function () {
        laydate.render({
            elem: '#timeBegin' //指定元素
            , type: 'datetime'
            , value: new Date(new Date().getTime() - 8 * 60 * 60 * 1000)
        });
        laydate.render({
            elem: '#timeEnd' //指定元素
            , type: 'datetime'
            , value: new Date()
        });
        $("#craneidinput").val(0);
        $("#tasktypeinput").val('');
        form.render();
        Page.searchAction();
    }


    /**
     * 表格的单击事件
     */
    Page.clickAction = function (obj) {

    }

    /**
     * 表格的双击事件
     */
    Page.doubleClickAction = function (obj) {

    }

    /**
     * 新增
     */
    Page.openAdd = function () {
        layer.open({
            type: 2,
            title: '新增',
            shadeClose: true,
            shade: 0.8,
            area: ['700px', '700px'],
            content: Page.addUrl,
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                //点击确认触发 iframe 内容中的按钮提交
                var submit = layero.find('iframe').contents().find("#form-btn-save");
                submit.click();

                //刷新表格
                Page.searchAction();
            }
        });
    };

    /**
     * 编辑
     */
    Page.openEdit = function (data) {
        layer.open({
            type: 2,
            title: '查看',
            shadeClose: true,
            shade: 0.8,
            area: ['700px', '700px'],
            content: Page.addUrl + "?id=" + data.id,
            btn: ['确定', '取消'],
            yes: function (index, layero) {
                //点击确认触发 iframe 内容中的按钮提交
                var submit = layero.find('iframe').contents().find("#form-btn-save");
                submit.click();

                //刷新表格
                Page.searchAction();
            }
        });
    };

    /**
     * 搜索按钮事件
     */
    $('#btnSearch').click(function () {
        Page.searchAction();
    });

//加载表格
    table.render({
        elem: '#' + Page.tableId
        , url: Page.url
        , page: true
        , limit: 10
        , autoSort: false
        , cols: Page.initColumn()
    });


    function updateTaskStatus(artificialId,status){
        //提交 Ajax进行后端删除
        $.ajax({
            type: "post",
            url: Page.changeStatusUrl,
            data: {artificialId: artificialId,
                status:status},
            success: function (res) {
                if (res.success) {
                    CXL.success(res.msg);
                    table.reload(Page.tableId);
                    // table.reload();
                } else {
                    CXL.warn(res.msg);
                    // layer.msg(res.msg);
                }
            }
        });

    }
});



